<template>
    <div :style="{marginTop:$store.state.navbarHeight+6+'px'}">
        <Navbar bgColor="bg-gradual-8" title="ئېچىش VIP" :showIcon="true" />
        <div class="container" :style="{marginTop:customBar()*2+12+'rpx'}">
            <div class="top-notice">پۈتۈن مەزمۇن ئالىي ئەزەلارغا ھەقسىز</div>
            <div class="price-wrap">
                <div class="item" :class="{active:(index==activeId)}" @click="changeBg(index)" v-for="(item,index) in priceList" :key="index">
                    <span>{{item.price}} يۈەن</span>
                    <span>ۋاقتى: {{item.time}} كۈن</span>
                </div>
                <div class="item" @click="intergalOrder" :class="[intergalBtn?'active':'']">
                    <span>50 جۇغلانما</span>
                    <span>1 كۈن</span>
                </div>
                <div style="width:30%;"></div>
                <div style="width:30%;"></div>
            </div>
            <div class="btn" @click="order" v-if="currGood">{{'ئېچىش'}}</div>
            <div class="btn" @click="orderByIntergal" v-if="intergalBtn">ئىلىتىماس قىلىش</div>
            <div class="tip">
                جۇغلانمىغا ئېرىشىش ئۇسۇلى: كۈندە يوقلامغا قاتناشسىڭىز 3 جۇغلانمىغا ئېرىشىسىز ، كىنونى دوستىڭىزغا ھەمبەھىرلىسىڭىز 1 جۇغلانمىغا ئېرىشەلەيسىز.</br>ئەگەر ئالىي ئەزالىق ئېچىشتا مەسىلىگە يولۇقسىڭىز بىز بىلەن ئالاقىلىشىڭ.
            </div>
        </div>
        <i-toast id="toast" />
    </div>
</template>

<script>
import Navbar from "@/components/Navbar.vue";
import { mapActions, mapGetters } from "vuex";
import { $orderNumber, $Toast, Base64, _decrypt } from "@/utils/index";
export default {
    beforeMount() {
        // let sys = wx.getStorageInfoSync();;
        /* if (this.$store.state.systemInfo.platform == "ios") {
            wx.navigateBack({
                delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
            });
            wx.showToast({
                title: "付费内容暂未向IOS用户开放", //提示的内容,
                icon: "none", //图标,
                duration: 2000, //延迟时间,
                mask: true, //显示透明蒙层，防止触摸穿透,
                success: res => {}
            });
        } */
    },
    components: {
        Navbar
    },
    data() {
        return {
            activeId: -1,
            priceList: [
                { price: 3, time: 1 },
                { price: 10, time: 15 },
                { price: 19, time: 30 },
                { price: 39, time: 90 },
                { price: 79, time: 180 },
                { price: 149, time: 365 }
            ],
            currGood: null,
            intergalBtn: false
        };
    },
    methods: {
        ...mapGetters(["customBar", "statusBar", "clientRect"]),
        changeBg(index) {
            if (this.intergalBtn) {
                this.intergalBtn = false;
            }
            if (this.activeId == index) {
                this.activeId = -1;
                this.currGood = null;
            } else {
                this.activeId = index;
                this.currGood = this.priceList[index];
            }
        },
        async order() {
            let sys = this.$store.state.systemInfo;
            /* if (!this.$store.state.config.iosPay && sys.platform == "ios") {
                wx.showModal({
                    title: "支付提示", //提示的标题,
                    content:
                        "由于相关规范，IOS功能暂不可用, بىز بىلەن ئايرىم ئالاقىلىشىپ سېتىۋېلىڭ", //提示的内容,
                    showCancel: false, //是否显示取消按钮,
                    confirmText: "知道了", //确定按钮的文字，默认为取消，最多 4 个字符,
                    confirmColor: "#3CC51F", //确定按钮的文字颜色,
                    success: res => {}
                });
                return;
            } */
            let orderId = $orderNumber(),
                openId = this.$store.state.userInfo.openId,
                payAmount = Math.round(this.currGood.price * 100);
            this.$http
                .post("/wxPay", { orderId, openId, total_fee: payAmount })
                .then(res => {
                    let { nonceStr, paySign, signType, timeStamp } = res;
                    var pack = res.package;

                    let startTime = Date.now(),
                        endTime =
                            startTime +
                            1000 * 60 * 60 * 24 * this.currGood.time;
                    let userInfo = {
                        uid: this.$store.state.userInfo.uid,
                        startTime,
                        endTime,
                        isVip: 1,
                        orderId,
                        openId,
                        payAmount
                    };
                    wx.requestPayment({
                        timeStamp, //时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间,
                        nonceStr, //随机字符串，长度为32个字符以下,
                        package: pack, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*,
                        signType, //签名算法，暂支持 MD5,
                        paySign, //签名,具体签名方案参见小程序支付接口文档,
                        success: res => {
                            let startTime = Date.now(),
                                endTime =
                                    startTime +
                                    1000 * 60 * 60 * 24 * this.currGood.time;
                            let userInfo = {
                                uid: this.$store.state.userInfo.uid,
                                startTime,
                                endTime,
                                isVip: 1,
                                orderId,
                                openId,
                                payAmount
                            };
                            /* let decodeStr = Base64.encode(
                                JSON.stringify(userInfo)
                            );
                            decodeStr = decodeStr
                                .replace(/A/g, "&")
                                .replace(/B/g, "%"); */
                            let decodeStr = Base64.encode(
                                JSON.stringify(userInfo)
                            );
                            decodeStr = decodeStr
                                .replace(/A/g, "&")
                                .replace(/B/g, "%");
                            this.$http
                                .post("/mpSetVip", { decodeStr })
                                .then(result => {
                                    if (result.code == "001") {
                                        this.updateUserInfo();
                                        $Toast({
                                            icon: "success",
                                            content:
                                                "ئالىي ئەزا بولغىنىڭىزنى تەبرىكلەيمىز",
                                            mask: true
                                        });
                                        setTimeout(() => {
                                            $Toast.hide();
                                        }, 3000);
                                    } else {
                                        wx.setClipboardData({
                                            data: "13122060027"
                                        });
                                        $Toast({
                                            content:
                                                "مەغلۇپ بولدى ،  ئۈندىدار كۆچۈرۈلدى ، بىز بىلەن ئالاقىلىشىڭ"
                                        });
                                        setTimeout(() => {
                                            $Toast.hide();
                                        }, 3000);
                                    }
                                });
                        },
                        fail: () => {
                            $Toast({
                                icon: "warning",
                                content: "مەغلۇپ بولدى"
                            });
                        },
                        complete: () => {}
                    });
                });
        },
        // 更新用户数据
        updateUserInfo() {
            let userInfo = wx.getStorageSync("userInfo");
            if (userInfo && userInfo.uid) {
                this.$http
                    .get("/mpGetUserStatus", { uid: userInfo.uid })
                    .then(res => {
                        if (res.code == "001") {
                            let infoStr = _decrypt(res.data, "yusupturak");
                            infoStr = Base64.decode(infoStr);
                            let info = JSON.parse(infoStr);
                            // 判断后端是否传了isVip字段
                            if (info && typeof info == "object" && info.isVip) {
                                this.$store.commit("SET_USER", info);
                            } else {
                                let now = Date.now();
                                if (
                                    info.startTime &&
                                    info.startTime < now &&
                                    info.endTime > now
                                ) {
                                    info.isVip = 1;
                                    {
                                        this.$store.commit("SET_USER", info);
                                    }
                                } else {
                                    this.$store.commit("SET_USER", info);
                                }
                            }
                        }
                    });
            }
        },
        // 积分用户
        intergalOrder() {
            this.intergalBtn = true;
            this.currGood = null;
            if (this.activeId != -1) {
                this.activeId = -1;
            }
        },
        async orderByIntergal() {
            try {
                let res = await this.$http.get("/mpApplyVip", {
                    uid: this.$store.state.userInfo.uid
                });
                if (res.code == "001") {
                    $Toast({
                        icon: res.icon,
                        content: res.msg
                    });
                } else {
                    $Toast({
                        icon: res.icon,
                        content: res.msg
                    });
                }
            } catch (error) {
                $Toast({
                    icon: "error",
                    content: "مەغلۇپ بولدى"
                });
            }
        }
    },
    onShareAppMessage() {
        return {
            title: "مارس كىنوخانىسى",
            path: `/pages/Home/Home`,
            success: res => {
                console.log("share-success");
            },
            fail: () => {
                console.log("share-fail");
            },
            complete: () => {}
        };
    }
};
</script>

<style lang="scss" scoped>
.container {
    display: block;
    border: 1px solid transparent;
    .top-notice {
        display: block;
        color: #666;
        text-align: center;
        margin-top: 24rpx;
    }
    .price-wrap {
        width: 98%;
        margin: 20rpx auto 0;
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;
        .item {
            border: 1rpx solid #3dabe8;
            border-radius: 15rpx;
            width: 30%;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 135rpx;
            margin-bottom: 20rpx;
            color: #3dabe8;
            direction: rtl;
            :first-child {
                margin: 10rpx 0;
            }
        }
        .active {
            background-color: #3dabe8;
            color: #ffffff;
        }
    }
    .btn {
        width: 95%;
        height: 80rpx;
        background: #0f97ff;
        border-radius: 44rpx;
        margin: 0 auto;
        line-height: 80rpx;
        text-align: center;
        color: white;
        font-size: 35rpx;
        margin-top: 19rpx;
        opacity: 0.9;
    }
}
.tip {
    direction: rtl;
    text-align: right;
    text-indent: 1em;
    padding: 10rpx;
    box-shadow: 0 0 15rpx 2rpx rgba(0, 0, 0, 0.15);
    width: 92%;
    margin: 0 auto;
    border-radius: 30rpx;
    border: 2rpx solid transparent;
    color: #999;
    margin-top: 30rpx;
}
</style>